package com.gemme.gemme.wode;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.PictureDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.util.DpUtil;
import com.gemme.gemme.util.ProgressUtil;
import com.gemme.gemme.view.OnChangeLIstener;
import com.gemme.gemme.view.RoundCheckBox;
import com.gemme.gemme.view.SwitchView;
import com.gemme.gemme.view.Topview;
import com.gemme.gemme.view.XydView;
import com.google.android.material.tabs.TabLayout;
import com.jaeger.library.StatusBarUtil;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

//侧滑删除地址
public class XinYuanDanActivity extends BaseActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xin_yuan_dan);
        initView();
        initData();
        initTop();
    }




    RecyclerView mRecyclerView;
    XydAdapter xydAdapter;
    float screen_width;
    float sh_width ;
    ImageView iv_more_xyz;
    TextView tv_duihuan;
    View rl_edit;
    SwitchView switchView;
    TextView tv_time;
    TextView tv_progress;
    ProgressBar progress_bar_h;
    View ll_progress;
    TextView tv_duihuan_recored;
    RoundCheckBox rb_bianjia;
    TextView tv_delete;
    private void initView() {

        iv_more_xyz = findViewById(R.id.iv_more_xyz);
        tv_duihuan = findViewById(R.id.tv_duihuan);
        mRecyclerView = findViewById(R.id.recycler);
        rl_edit = findViewById(R.id.rl_edit);

        switchView = findViewById(R.id.switchView);
        tv_time = findViewById(R.id.tv_time);
        tv_progress = findViewById(R.id.tv_progress);
        progress_bar_h = findViewById(R.id.progress_bar_h);

        ll_progress = findViewById(R.id.ll_progress);



        rb_bianjia = findViewById(R.id.rb_bianjia);

        tv_duihuan_recored = findViewById(R.id.tv_duihuan_recored);


        tv_delete = findViewById(R.id.tv_delete);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        new LinearSnapHelper().attachToRecyclerView(mRecyclerView);


        initListener();



        Display defaultDisplay = getWindowManager().getDefaultDisplay();
        Point point = new Point();
        defaultDisplay.getSize(point);

        screen_width = point.x;
        sh_width = screen_width / 2;

        iv_more_xyz.setOnClickListener(this);
        tv_duihuan.setOnClickListener(this);

        switchView.setOnSwitchChange(new SwitchView.OnSwitchChange() {
            @Override
            public void OnSwitchChange(boolean isOn) {
                detailIsOpen(isOn);
            }
        });

        tv_duihuan_recored.setOnClickListener(this);

        rb_bianjia.setOnChangeLIstener(new OnChangeLIstener() {
            @Override
            public void onChangeLIstener() {
                isAllCheck = rb_bianjia.isChecked();

                if(xydAdapter != null){
                    List<XydBean.DataBean.RecordsBean> data = xydAdapter.getData();
                    if(data == null || data.size() == 0)
                        return;
                    for (int i = 0; i < data.size(); i++) {
                        data.get(i).setCheck(isAllCheck);
                    }
                    xydAdapter.notifyDataSetChanged();
                }

            }
        });


        tv_delete.setOnClickListener(this);
    }



    List<XydBean.DataBean.RecordsBean> records;
    private void initData() {
        String url = DataManager.BaseUrl_yanglinyu + "mall/shopwish/app/list?current=1&size=100" ;

        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(this));
        DataManager.toServer2(this, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    XydBean xydBean = JSON.parseObject(response, XydBean.class);

                    records = xydBean.getData().getRecords();
                    if(records == null || records.size() == 0){
                        ll_progress.setVisibility(View.GONE);
                        topview.getRightText().setVisibility(View.GONE);
                        return;
                    }else{
                        ll_progress.setVisibility(View.VISIBLE);
                        topview.getRightText().setVisibility(View.VISIBLE);
                    }

                   setReclycle();

                }catch (Exception e){
                    ll_progress.setVisibility(View.GONE);
                }
            }
        });
    }

    private void setReclycle() {
        xydAdapter = new XydAdapter(records);
        mRecyclerView.setAdapter(xydAdapter);

        mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                onScrolledChangedCallback();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_more_xyz:
//                startActivity(new Intent(mContext,XyzGuizeActvity.class));
                startActivity(new Intent(mContext,XyzgzActivity.class));
                break;

            case R.id.tv_duihuan:
//                startActivity(new Intent(mContext,XyzGuizeActvity.class));
//                startActivity(new Intent(mContext, XydRecordActivity.class));
                duihuan();
                break;


            case R.id.tv_duihuan_recored:
                startActivity(new Intent(mContext, XydRecordActivity.class));
                break;

            case R.id.tv_delete:
                deleteXinyuandan();
                break;
        }
    }



    int currentPosition = 0;

    private void initListener() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);



            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // dx>0则表示右滑, dx<0表示左滑, dy<0表示上滑, dy>0表示下滑

                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取第一个可见view的位置
                    int firstItemPosition = linearManager.findFirstVisibleItemPosition();

                    //获取最后一个可见view的位置
                    int lastItemPosition = linearManager.findLastVisibleItemPosition();

                    if(lastItemPosition - firstItemPosition == 2){
                        currentPosition = firstItemPosition + 1;
                    }else{
                        currentPosition = firstItemPosition;
                    }
                }

                System.out.println("currentPosition : " + currentPosition);
                onScrolledChangedCallback();

                controlBottom();
            }
        });


    }

    private void controlBottom() {
        try {
          /*  switchView
                    tv_time
            tv_progress
                    progress_bar_h*/

            XydBean.DataBean.RecordsBean recordsBean = (XydBean.DataBean.RecordsBean)selectView.getTag();
            boolean isOpen = recordsBean.getStatus() == 0 ? true : false;
            switchView.setState(isOpen);
            tv_time.setText(recordsBean.getCreateTime() + "");
            int wishValue = recordsBean.getWishValue();


            if(wishValue >= 100){
                tv_progress.setText(100+"%");
                progress_bar_h.setProgress(wishValue);
            }else{
                tv_progress.setText(wishValue+"%");
                progress_bar_h.setProgress(wishValue);
            }


            if(isOpen){
//                progress_bar_h.setProgressDrawable(new BitmapDrawable(getResources().getResourceName(R.drawable.progressbar_bg)));
                ProgressUtil.setProgressDrawable(progress_bar_h, R.drawable.progressbar_bg);
                tv_progress.setTextColor(Color.parseColor("#ff9d2c2f"));
                tv_duihuan.setTextColor(Color.parseColor("#ff9d2c2f"));//#FFE9E9EB
            }else{
//                progress_bar_h.setProgressDrawable(new BitmapDrawable(getResources().getResourceName(R.drawable.progressbar_bg_normal)));
                ProgressUtil.setProgressDrawable(progress_bar_h, R.drawable.progressbar_bg_normal);
                tv_progress.setTextColor(Color.parseColor("#FFE9E9EB"));
                tv_duihuan.setTextColor(Color.parseColor("#FFE9E9EB"));//#FFE9E9EB
            }



        }catch (Exception e){

        }
    }

    private void onScrolledChangedCallback() {
        View leftView = null;
        View currentView;
        View rightView = null;
        if(currentPosition < 0)
            return;

        if (currentPosition > 0) {
            leftView = mRecyclerView.getLayoutManager().findViewByPosition(currentPosition - 1);
        }
        currentView = mRecyclerView.getLayoutManager().findViewByPosition(currentPosition);
        if (currentPosition < mRecyclerView.getAdapter().getItemCount() - 1) {
            rightView = mRecyclerView.getLayoutManager().findViewByPosition(currentPosition + 1);
        }

        try {
          /*  leftView.setScaleY(0.8f);
            currentView.setScaleY(1.1f);
            rightView.setScaleY(0.8f);*/

            control(leftView);
            control(currentView);
            control(rightView);


        }catch (Exception e){

        }
    }
    View selectView;
    private void control(View view) {
        if(view == null)
            return;
        float left = view.getLeft();
        float right = view.getRight();
        System.out.println();

        float view_half = (left + right) / 2;
        float abs = Math.abs(view_half - sh_width);
        if(abs >=  sh_width){
            view.setScaleY(0.8f);
        }else{
            //  540
            float scale_size = 1 - Math.abs((((sh_width - view_half) / sh_width) * (1 - 0.8f)));
            view.setScaleY(scale_size);
        }

        if(sh_width > left && sh_width < right){

            selectView = view;
        }
    }

    boolean isEdit = false;
    TextView top_rightText;
    Topview topview;
    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);
        topview = findViewById(R.id.topview);
        topview.setContentText("心愿单");
        top_rightText = topview.getRightText();
        changeState();
        topview.getRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isEdit = !isEdit;
                changeState();
            }
        });
    }

    private void changeState() {
        if(isEdit){//
            topview.setRightText("完成");
            rl_edit.setVisibility(View.VISIBLE);
        }else{
            topview.setRightText("编辑");
            rl_edit.setVisibility(View.GONE);
        }

        if(xydAdapter != null)
        xydAdapter.notifyDataSetChanged();
    }


    public  class XydAdapter extends RecyclerView.Adapter<XydAdapter.ViewHolder>{
        private List<XydBean.DataBean.RecordsBean> adapterList;

        //        List<XydBean.DataBean.RecordsBean> records
        public XydAdapter(List<XydBean.DataBean.RecordsBean> adapterList){

            this.adapterList = adapterList;
        }

        public List<XydBean.DataBean.RecordsBean> getData(){
            return adapterList;
        }

        @NonNull
        @Override
        public XydAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.item_gallery, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.leftMargin = DpUtil.dip2px(mContext,15);
            layoutParams.rightMargin = DpUtil.dip2px(mContext,15);
            inflate.setLayoutParams(layoutParams);
            return new XydAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull XydAdapter.ViewHolder holder, int position) {
            Log.e("@@@@@@",""+adapterList.size());
            if(adapterList.size()==1){
                Log.e("#######",""+adapterList.size());
                holder.view_add_paddding.setVisibility(View.VISIBLE);
                holder.view_add_paddding_1.setVisibility(View.VISIBLE);
                holder.view_add_paddding_right.setVisibility(View.GONE);
            }else {
                if(position == 0){
                    holder.view_add_paddding.setVisibility(View.VISIBLE);
                }else{
                    holder.view_add_paddding.setVisibility(View.GONE);
                }

                if(position == adapterList.size() -1){
                    holder.view_add_paddding_right.setVisibility(View.VISIBLE);
                }else{
                    holder.view_add_paddding_right.setVisibility(View.GONE);
                }
            }
            XydBean.DataBean.RecordsBean recordsBean = adapterList.get(position);
            holder.itemView.setTag(recordsBean);
            int status = recordsBean.getStatus();
            if(status == 0){//心愿单被开启
                holder.xydview.start();
            }else{//心愿单被关闭
                holder.xydview.stop();
            }

            holder.xydview.setState(recordsBean.isCheck());

            holder.xydview.setCbVisible(isEdit ? View.VISIBLE : View.GONE);

            holder.xydview.setImage(recordsBean.getAbbreviationPic());
            holder.xydview.setName(recordsBean.getProductName()).setPrice(recordsBean.getPrice());

            //监听是否选中
            holder.xydview.setOnChangeLIstener(new OnChangeLIstener() {
                @Override
                public void onChangeLIstener() {
                    boolean state = holder.xydview.getState();
                    recordsBean.setCheck(state);
                    isAllCheck(adapterList);
                    rb_bianjia.setChecked(isAllCheck);
                }
            });

            //监听收取
            holder.xydview.setOnwishvaluecharge(new OnChangeLIstener() {
                @Override
                public void onChangeLIstener() {
                    initData();
                }
            });
        }

        @Override
        public int getItemCount() {
            return adapterList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            View view_add_paddding;
            View view_add_paddding_1;
            View view_add_paddding_right;
            XydView xydview;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                view_add_paddding = itemView.findViewById(R.id.view_add_paddding);
                view_add_paddding_1 = itemView.findViewById(R.id.view_add_paddding_1);
                view_add_paddding_right = itemView.findViewById(R.id.view_add_paddding_right);
                xydview = itemView.findViewById(R.id.xydview);
            }
        }
    }

    boolean isAllCheck = false;
    private void isAllCheck(List<XydBean.DataBean.RecordsBean> adapterList) {
        try {
            if(adapterList == null || adapterList.size() == 0)
                return;
            for (int i = 0; i < adapterList.size(); i++) {
                XydBean.DataBean.RecordsBean recordsBean = adapterList.get(i);
                if(!recordsBean.isCheck()){
                    isAllCheck = false;
                    return;
                }
            }

            isAllCheck = true;

        }catch (Exception e){

        }
    }

    private void detailIsOpen(boolean isOn) {
        try {
            XydBean.DataBean.RecordsBean recordsBean = (XydBean.DataBean.RecordsBean)selectView.getTag();
            int id = recordsBean.getId();
            int status = isOn ? 0 : 1;


            String url = DataManager.BaseUrl_yanglinyu + "mall/shopwish/app/edit?id=" + id
                    + "&status="+status;

            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey,DataManager.getToken(this));
            DataManager.toServer3(this, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    try{
                        if(DataPares.isSucess(mContext,response)){
                            String msg = (new JSONObject(response)).getString("msg");
                            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                        }else{
                            String msg = (new JSONObject(response)).getString("msg");
                            String data = (new JSONObject(response)).getString("data");

                            Toast.makeText(mContext, msg + data, Toast.LENGTH_SHORT).show();
                        }

                        initData();

                    }catch (Exception e){

                    }
                }
            });
        }catch (Exception e){

        }
    }

    private void duihuan() {
        try {
            XydBean.DataBean.RecordsBean recordsBean = (XydBean.DataBean.RecordsBean)selectView.getTag();
            int id = recordsBean.getId();


            String url = DataManager.BaseUrl_yanglinyu + "mall/shopwish/app/exchange?id=" + id;

            HashMap<String, String> headMap = new HashMap<>();
            headMap.put(DataManager.AuthorizationKey,DataManager.getToken(this));
            DataManager.toServer3(this, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
                @Override
                public void onResponse(String response) {
                    try{
                        if(DataPares.isSucess(mContext,response)){
                            String msg = (new JSONObject(response)).getString("msg");
                            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                        }else{
                            String msg = (new JSONObject(response)).getString("msg");
                            String data = (new JSONObject(response)).getString("data");

                            Toast.makeText(mContext, msg + data, Toast.LENGTH_SHORT).show();
                        }

                        initData();

                    }catch (Exception e){

                    }
                }
            });
        }catch (Exception e){

        }
    }


    private void deleteXinyuandan() {
      try {
          String url;
          if(isAllCheck){
              url = DataManager.BaseUrl_yanglinyu + "mall/shopwish/app/delete";
          }else{
              String idstr = "";
              if(xydAdapter == null || xydAdapter.getData() == null || xydAdapter.getData().size() == 0)
                  return;
              List<XydBean.DataBean.RecordsBean> data = xydAdapter.getData();
              for (int i = 0; i < data.size(); i++) {
                  XydBean.DataBean.RecordsBean recordsBean = data.get(i);
                  int id = recordsBean.getId();
                  if(!recordsBean.isCheck())
                      continue;

                  if(TextUtils.isEmpty(idstr)){
                      idstr = idstr + id;
                  }else{
                      idstr = idstr + "," + id;
                  }
              }
              url = DataManager.BaseUrl_yanglinyu + "mall/shopwish/app/delete?productName=" + idstr;


          }




          HashMap<String, String> headMap = new HashMap<>();
          headMap.put(DataManager.AuthorizationKey,DataManager.getToken(this));
          DataManager.toServer2(this, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
              @Override
              public void onResponse(String response) {
                  try{


                      if(DataPares.isSucess(mContext,response)){
                          String msg = (new JSONObject(response)).getString("msg");
                          Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                      }

                  }catch (Exception e){

                  }

                  initData();

              }
          });
      }catch (Exception e){

      }
    }


}